import {createSlice} from '@reduxjs/toolkit';
import {AppThunk, RootState, store} from './store.ts';
import {get, injectApi, rejectApi} from '../http/http.tsx';
import config from '../config/config.js';
import {ToastAndroid} from 'react-native';
import DeviceInfo from 'react-native-device-info';
import {
  login,
  fetchData,
  loginTeacherAPI,
  loginInnerTeacherAPI,
} from '../http/api.ts';

// 1、定义state
interface RootState {
  value: any;
  user: any;
}

// 2、state的初始值定义
const initialState: RootState = {
  value: null,
  user: null,
};

// 3、创建slice
export const rootSlice = createSlice({
  // 3.1 slice名称
  name: 'root',
  // 3.2 state初始值
  initialState,
  // 3.3 使用action函数填充reducers
  reducers: {
    beginLoading: () => {
      console.log('开始加载初始');
    },
    notBinding: (state, {payload}) => {
      console.log('开始加载初始');
      state.value = null;
    },
    finishLoading: (state, {payload}) => {
      state.value = payload;
      rejectApi('channel');
      injectApi('channel', (config: any) => {
        try {
          console.log('channel注入', config.headers, config.params);
          config.headers = {
            ...config.headers,
            channelId: payload.electronicClassCardBind.channelId,
          };
          if (config.params) {
            config.params = {
              ...config.params,
              channelId: payload.electronicClassCardBind.channelId,
            };
          }
          if (config.data) {
            config.data = {
              ...config.data,
              channelId: payload.electronicClassCardBind.channelId,
            };
          }
        } catch (e) {
          console.log(e);
        }
      });
    },
    finishLoadManager: (state, {payload}) => {
      state.user = payload;
      console.log('结束加载:', payload);
      ToastAndroid.show('登录成功', ToastAndroid.SHORT);
      rejectApi('token');
      injectApi('token', config => {
        try {
          console.log('config.data', config.data);
          console.log('payload', payload);
          console.log('token注入', config.headers, config.params);
          config.headers = {...config.headers, token: payload.token};
          if (config.params) {
            config.params = {
              ...config.params,
              token: payload.token,
            };
          }
          if (config.data) {
            config.data = {...config.data, token: payload.token};
          }
        } catch (e) {
          console.log(e);
        }
      });
    },
    logoutUser: state => {
      state.user = null;
      rejectApi('token');
    },
  },
});

// 4、导出actions，为了能够在外部访问到
export const {
  beginLoading,
  finishLoading,
  finishLoadManager,
  logoutUser,
  notBinding,
} = rootSlice.actions;

// 5、异步函数，网络请求可以参考
export const fetchRootData = (): AppThunk => async dispatch => {
  // 5.1 开始加载处理，可以Loading提示
  dispatch(beginLoading());
  // 5.2 模拟网络请求获取数据
  fetchData()
    .then(data => {
      // 5.3网络请求结束后更新结果
      dispatch(finishLoading(data));
    })
    .catch(err => {
      ToastAndroid.show(err.message, ToastAndroid.SHORT);
      config.DEVICE_ID = DeviceInfo.getUniqueIdSync() + '1';
      // 再重试一次
      fetchData()
        .then(data => {
          // 5.3网络请求结束后更新结果
          dispatch(finishLoading(data));
        })
        .catch(error => {
          config.DEVICE_ID = DeviceInfo.getUniqueIdSync();
          // console.log(`请求失败 ${error}`);
          console.log('---->', error);
          ToastAndroid.show(error.message, ToastAndroid.LONG);
          dispatch(notBinding(true));
        });
    });
};

export const logout = () => dispatch => {
  dispatch(logoutUser());
};

export const loginManager =
  (username, password, loginComplete): AppThunk =>
  async dispatch => {
    // 5.1 开始加载处理，可以Loading提示
    dispatch(beginLoading());
    login(username, password)
      .then(data => {
        // 5.3网络请求结束后更新结果
        dispatch(finishLoadManager(data));
        loginComplete && loginComplete();
      })
      .catch(err => {
        ToastAndroid.show(err.message, ToastAndroid.LONG);
        console.log(`请求失败 ${err}`);
      });
  };

export const loginTeacher =
  (username, password, loginComplete): AppThunk =>
  async dispatch => {
    // 5.1 开始加载处理，可以Loading提示
    dispatch(beginLoading());
    loginTeacherAPI(username, password)
      .then(data => {
        // 5.3网络请求结束后更新结果
        dispatch(finishLoadManager(data));
        loginComplete && loginComplete();
      })
      .catch(err => {
        ToastAndroid.show(err.message, ToastAndroid.LONG);
        console.log(`请求失败 ${err}`);
      });
  };

export const loginInnerTeacher =
  (userId: string, loginComplete: any): AppThunk =>
  async dispatch => {
    // 5.1 开始加载处理，可以Loading提示
    dispatch(beginLoading());
    loginInnerTeacherAPI(userId)
      .then(data => {
        // 5.3网络请求结束后更新结果
        dispatch(finishLoadManager(data));
        loginComplete && loginComplete();
      })
      .catch(err => {
        ToastAndroid.show(err.message, ToastAndroid.LONG);
        console.log(`请求失败 ${err}`);
      });
  };
// 6、定义selector函数，访问state中某个变量
// 当value值被更新，使用到该selector函数的组件也会重新渲染
export const selectRoot = (state: RootState) => state.root.value;

// 7、导出reducer，在index.ts中组装成最终的store
export default rootSlice.reducer;
